<template>
    <div>
        <el-form :rules="rules" :model="user" class="loginFrom" ref="loginRef">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="user.username" clearable></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="user.password" show-password clearable></el-input>
            </el-form-item>
            <el-button @click="Login" class="login" @keyup.enter="Login">登 录</el-button>
        </el-form>
    </div>
</template>
<script>
import { adminLogin } from "../request/api";
export default {
    data() {
        return {
            user: {
                username: '',
                password: ''
            },
            // 验证规则对象
            rules: {
                username: [
                    { required: true, message: '请输入用户名称', trigger: 'blur' },
                    { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
                ]
            }
        }
    },
    methods: {
        // 封装一个登录事件
        Login() {
            // 规则验证
            this.$refs.loginRef.validate((val) => {
                console.log(val)
                if (val) {
                    // 调用接口
                    adminLogin(this.user).then(res => {
                        if (res.code == 200) {
                            console.log(res);
                            this.$message.success(res.msg)
                            // 把登录信息存储到仓库中
                            this.$store.dispatch('changeUserInfo', res.list)
                            // 验证成功跳转首页
                            setTimeout(() => {
                                this.$router.push('/index')
                            }, 1500);
                           
                        } else {

                        }
                    })
                    console.log(this.user)
                }
            })

        },
        keyDown(e) {
            if (e.keyCode == 13) {
                this.Login()
            }
        }
    },
    mounted() {
        //绑定监听事件 
        window.addEventListener("keydown", this.keyDown);

    },
    watch: {},
    computed: {},
    filters: {},
    components: {}
}
</script>
<style lang="less" scoped>
.loginFrom {
    position: absolute;
    width: 400px;
    height: 300px;
    margin: 250px 0 0 350px;
}

.login {
    border: none;
    width: 100px;
    height: 50px;
    text-align: center;
    margin-left: 150px;
    background-color: coral;
    font-size: 20px;
}
</style>